package com.fizzback.utils
{
	import flash.display.GradientType;
	import flash.display.Graphics;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	
	import mx.graphics.GradientBase;
	import mx.graphics.GradientEntry;
	import mx.graphics.LinearGradient;
	
	import spark.effects.interpolation.RGBInterpolator;

	/**
	 *	@author "oleksandr.kulinchenko@gmail.com"
	 */
	public class ColorsHelper
	{
		public function ColorsHelper()
		{
		}
		
		//{region COLORING
		[Bindable]private var color:uint;			
		private static var redBias:Number = 0xFF;
		private static var greenBias:Number = 0xFF;
		private static var blueBias:Number = 0xFF;			
		public static function getRandomColor():uint{
			var ct:ColorTransform = new ColorTransform(1, 1, 1, 1, Math.random()*redBias, Math.random()*greenBias, Math.random()*blueBias);
			var color:uint = ct.color;
			return color;
		}
		//}endregion
		
		/**
		 * Temporary conversion of LinearGradient structure to Graphics#beginGradientFill parameters
		 */
		public static function beginGradientFill(graphics:Graphics, gradient:GradientBase, matrix:Matrix):void{
			var colors:Array=[], alphas:Array=[], ratios:Array=[];
			for each(var entry:GradientEntry in gradient.entries){
				colors.push(entry.color);
				alphas.push(entry.alpha);
				ratios.push(entry.ratio*255);				
			}
			graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, matrix);
			
		}
		
		
		public static function getGradientFractionColor(fraction1:Number, gradient:GradientBase):uint{
			var fr:Number=1-fraction1;
		
			var entry1:GradientEntry, entry2:GradientEntry;
			var arr:Array = gradient.entries;
			var sety:Boolean=false;
			for(var i:uint=1; i<arr.length; i++){
				entry1 = arr[i-1] as GradientEntry;
				entry2 = arr[i] as GradientEntry;
				trace("ratio=>s"+[entry1.ratio, entry2.ratio, fr]);
				if(fr>=entry1.ratio && fr<entry2.ratio){
					sety=true;
					break;
				}
			}
			
			if(!sety){
				trace("AAAAA"+[entry1.ratio, entry2.ratio, fr]);
			}
			//trace([fraction, entry1.ratio, entry2.ratio]);
			var colorFraction:Number = (fr-entry1.ratio)/(entry2.ratio-entry1.ratio);
			trace("CLR->"+[entry1.ratio, entry2.ratio, fr, colorFraction]);
			var color:uint = RGBInterpolator.getInstance().interpolate(colorFraction, entry1.color, entry2.color) as uint;
			return color;
		}
		
	}
}